package work.zhengyun.demo.pub_sub;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhengyun
 * @date 2019/11/22 16:27
 */
@EnableScheduling //开启定时器功能
@Component
public class MessageSender {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(fixedRate = 200000) //间隔200s 通过StringRedisTemplate对象向redis消息队列chat频道发布消息
    public void sendMessage(){
        stringRedisTemplate.convertAndSend("chat",String.valueOf(Math.random()));
    }

    @RequestMapping("/sendmessage2")
    /* @ResponseBody
    将方法的返回值，以特定的格式写入到response的body区域，进而将数据返回给客户端。
    当方法上面没有写ResponseBody,底层会将方法的返回值封装为ModelAndView对象。
    如果返回值是字符串，那么直接将字符串写到客户端；如果是一个对象，会将对象转化为json串，然后写到客户端。
     */
    @ResponseBody
    public String sendMessage2(){
        stringRedisTemplate.convertAndSend("chat","哈哈哈");
        return "ok2";
    }
    @RequestMapping("/sendmessage3")
    @ResponseBody
    public String sendMessage3(){
        stringRedisTemplate.convertAndSend("sendUser","哈哈哈");
        return "ok3";
    }
}
